package com.isoft.c2team3service2.util;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.isoft.c2team3service2.config.AlipayConfig;
import com.isoft.c2team3service2.config.AlipayProperties;
import com.isoft.c2team3service2.entity.MemberOrder;
import com.isoft.c2team3service2.entity.Order;
import com.isoft.c2team3service2.entity.PayRecord;
import com.isoft.c2team3service2.mapper.MemberOrderMapper;
import com.isoft.c2team3service2.mapper.OrderMapper;
import com.isoft.c2team3service2.mapper.PayRecordMapper;
import com.isoft.c2team3service2.service.OrderService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author 蓝莓
 * @date 2025/10/31 9:12
 */
@Controller
public class Alipay {

    @Autowired
    private PayRecordMapper payRecordMapper;

    private static AlipayProperties alipayProperties;

    @Autowired
    public void setAlipayProperties(AlipayProperties alipayProperties) {
        Alipay.alipayProperties = alipayProperties;
    }

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private MemberOrderMapper memberOrderMapper;

    public static void createAliPay(String payNo, HttpServletResponse response, BigDecimal price, String name) throws Exception {
        AlipayClient alipayClient = new DefaultAlipayClient(
                AlipayConfig.URL,
                alipayProperties.getAppId(),
                alipayProperties.getAppPrivateKey(),
                AlipayConfig.FORMAT,
                AlipayConfig.CHARSET,
                alipayProperties.getAlipayPublicKey(),
                AlipayConfig.SIGNTYPE
        );
        //TODO
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();//创建API对应的request
        alipayRequest.setNotifyUrl("http://x3689fd4.natappfree.cc/paynotify");//在公共参数中设置回跳和通知地址
        alipayRequest.setBizContent("{" +
                "    \"out_trade_no\":\""+payNo+"\"," +
                "    \"total_amount\":"+ price +"," +
                "    \"subject\":\""+"顾客 "+ name + " 的订单" +"\"," +
                "    \"product_code\":\"QUICK_WAP_WAY\"" +
                "  }");//填充业务参数
        String form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK请求支付宝下单
        response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
        response.getWriter().write(form);//直接将完整的表单html输出到页面
        response.getWriter().flush();
    }

    /**
     * 查询支付结果
     */
    @PostMapping("/paynotify")
    public boolean paynotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String,String> params = new HashMap<>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }


        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
        //计算得出通知验证结果
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean verify_result = AlipaySignature.rsaCheckV1(params, alipayProperties.getAlipayPublicKey(), AlipayConfig.CHARSET, "RSA2");

        if(verify_result) {//验证成功
            //////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代码

            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //支付宝交易号
            //用来对账
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

            if (trade_status.equals("TRADE_SUCCESS")) {//交易成功
                System.out.println(trade_status);
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                //如果有做过处理，不执行商户的业务程序
                System.out.println(trade_status);
                System.out.println(out_trade_no);
                System.out.println(trade_no);

                PayRecord payRecord= payRecordMapper.selectOne(new QueryWrapper<PayRecord>().eq("pay_no", out_trade_no));
                if ( payRecord != null) {
                    Integer orderId = payRecord.getOrderId();

                    payRecord.setOutPayNo(trade_no);
                    payRecord.setOutPayChannel("alipay");
                    payRecord.setPaySuccessTime(LocalDateTime.now());
                    payRecord.setStatus("paid");
                    payRecordMapper.updateById(payRecord);

                    Order order = new Order();
                    order.setId(orderId);
                    order.setStatus("paid");
                    orderMapper.updateById(order);
                    //注意：
                    //如果签约的是可退款协议，那么付款完成后，支付宝系统发送该交易状态通知。

                    return true;
                } else {
                    MemberOrder memberOrder = new MemberOrder();
                    memberOrder.setId(memberOrderMapper.selectOne(new QueryWrapper<MemberOrder>().
                            eq("order_no", out_trade_no)).
                            getId());
                    memberOrder.setPayStatus(1);
                    memberOrder.setPayTime(LocalDateTime.now());
                    memberOrderMapper.updateById(memberOrder);
                    return true;
                }
            }
            response.getWriter().write("success");
        }else{
            response.getWriter().write("fail");
            return false;
        }
        return false;
    }
}
